<script>

class Node{
    constructor(data){
        this.data = data
        this.next = null
        this.prev = null
    }
}
class DoublyLinkedList{
    constructor(){
        this.head = null
        this.tail = null
    }
    add(item) {
        let node = new Node(item)
        if(!this.head){
            this.head = node
            this.tail = node
        }else{
            this.tail.next = node
            node.prev = this.tail
            this.tail = node
        }
    }
    //在链表指定位置添加一个节点
    addAt(index, item){
        let current = this.head
        let counter = 0
        let node = new Node(item)
        
        if(index === 0){
            this.head.prev = node
            node.next = this.head
            this.head = node
        }else{
            while(current){
                counter++
                current = current.next
                if(counter === index){
                    node.next = current
                    node.prev = current.prev
                    current.prev.next = node
                    current.prev = node
                }
            }
        }
    }
    //删除指定数据节点
    remove(item){
        let current = this.head
        while(current){
            if(current.data === data){
                if(current === this.head && current === this.tail){
                    this.head = null
                    this.tail = null
                }else if(current === this.head){
                    this.head = this.head.next
                    this.head.prev = null
                }else if(current === this.tail){
                    this.tail = this.tail.prev
                    this.tail.next = null
                }else{
                    current.prev.next = current.next
                    current.next.prev = current.prev
                }
            }
            current = current.next
        }
    }
    //删除指定位置节点
    remove(index){
        let current = this.head
        let counter = 0
        if(index === 0){
            this.head = this.head.next
            this.head ? this.head.prev = null : this.tail = null
        }else{
            while(current.next){
                current = current.next
                counter++
                if(counter === index){
                    if(current === this.tail){
                        this.tail = this.tail.prev
                        this.tail.next = null
                    }else{
                        current.next.prev = current.prev
                        current.prev.next = current.next
                    }
                    break
                }
            }
        }
    }
    //反转链表
    reverse(){
        let current = this.head
        let prev = null
        while(current){
            current.prev = current.next
            current.next = prev
            prev = current
            current = current.prev
        }
    }
}



</script>